<script setup>
import {Delete, Download, Edit, Plus, Search, Upload} from "@element-plus/icons-vue";
import {reactive, ref, onMounted} from "vue";
import {addAccount, listAccount} from "@/api/game/gameInfo";
import {updateUser} from "@/api/system/user";
import {ElMessage} from "element-plus";
import {validEmail} from "@/utils/validUtil";

const ruleFormRef = ref(null)
const accountList = ref([])
const openDialog =ref(false)
const loading = ref(false)
//总条数
const total = ref(0)
//总页数
const pages = ref("1")
const queryParams = reactive({
  pageSize: 10,//显示条数
  currentPage: 1,//当前页面
  gameAccount: undefined,
  status: undefined
})
const form = reactive({
  gameAccount: '',
  nickname: '',
  status: '',
  date: [],
})

const accountFrom = reactive({
  gameInfo:{
    id: undefined,
    nickname: '',
    gameAccount: '',
    gamePassword: '',
    serverType: 0,
    status: 0,
    remark:'',
  },
  email: '',

})
const add=() =>{
  clearFrom();
  dialogTitle.value = '添加账号'
  accountFrom.gameInfo.gameAccount= ''
  accountFrom.gameInfo.gamePassword= ''
  openDialog.value = true;
}
const clearFrom = () =>{
  accountFrom.gameInfo.id = undefined
  accountFrom.gameInfo.nickname= ''
  accountFrom.gameInfo.gameAccount= ''
  accountFrom.gameInfo.gamePassword= ''
  accountFrom.gameInfo.remark= ''
  accountFrom.email = ''
}
onMounted(() => {
  getList()
})

const getList = (tableData) => {
  loading.value = true;
  listAccount().then(res => {
        const data = res.data;
        accountList.value = data.records;
        total.value = data.total;
        queryParams.pageSize = data.size;
        queryParams.currentPage = data.current
        pages.value = data.pages
        loading.value = false;
      }
  );
}
const handleSizeChange = (pageSize) => {
  queryParams.pageSize = pageSize;
  getList(queryParams)
}
const handleCurrentChange = (currentPage) => {
  queryParams.currentPage = currentPage;
  getList(queryParams)
}
const validateUsername = (rule, value, callback) => {
  const regexp=/^[a-zA-Z0-9]{5,11}$/
  if (!value) {
    callback(new Error('请输入账号'))
  } else if (!regexp.test(value)){
    callback(new Error('用户名必须为5-11位字母、数字组成'))
  }else{
    callback()
  }
}
/**
 * 密码校验
 * @param rule
 * @param value
 * @param callback
 */
const validatePassword = (rule, value, callback) => {
  const regexp=/^[a-zA-Z0-9.@#]{6,20}$/
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (!regexp.test(value)) {
    callback(new Error('密码长度为6-20位字母、数字、符号(.@#)'))
  }else {
    callback()
  }
}
/**
 * 校验邮箱
 * @param rule
 * @param value
 * @param callback
 */
const validateEmail = (rule, value, callback) => {
  // 校验是否格式不正确
  if (!validEmail(value)) {
    callback(new Error('邮箱格式不符')); // 错误情况，返回错误信息
  }
  else {
    callback(); // 这里 callback 不带参数表示校验通过
  }
};
const validateNickname = (rule, value, callback) => {
  const regexp=/^[a-zA-Z0-9.@#]{0,30}$/
  if (!regexp.test(value)) {
    callback(new Error('昵称长度为0-30位字符'))
  }else {
    callback()
  }
};
const rules = reactive({
  gameAccount: [{ validator: validateUsername, trigger: 'blur' }],
  gamePassword: [{ validator: validatePassword, trigger: 'blur' }],
  email: [{ validator: validateEmail, trigger: 'blur' }],
  nickname: [{ validator: validateNickname, trigger: 'submit' }],
})
// 弹出框标题
const dialogTitle = ref('')
const handleClick =(formEl,row)=>{
  if (!formEl) return
  formEl.validate((valid) => {
    if (accountFrom.gameInfo.id){
      updateUser(accountFrom.gameInfo).then((res) =>{
        ElMessage.success(res.message)
        getList(queryParams)
        openDialog.value = false
      }).catch(()=>{
      })
    }else {
      //添加用户操作
      dialogTitle.value = '添加账号'
      addAccount(accountFrom).then((res)=>{
        ElMessage.success(res.message)
        openDialog.value = false
        getList(queryParams)
      }).catch(()=>{
      })
    }
  })
}
const reftest=ref(null);
const onSubmit = () => {
  console.log(reftest.value)

}

</script>

<template>
  <div class="box">
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="游戏账号">
        <el-input style="width: 150px" v-model="form.gameAccount" placeholder="游戏账号" clearable/>
      </el-form-item>
      <el-form-item label="账号昵称">
        <el-input style="width: 150px" v-model="form.nickname" placeholder="账号昵称" clearable/>
      </el-form-item>
      <el-form-item label="选择状态">
        <el-select
            style="width: 120px"
            v-model="form.status"
            placeholder="选择状态"
            clearable>
          <el-option label="正常" value="0"/>
          <el-option label="停用" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
            v-model="form.date"
            style="width: 200px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :icon="Search">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            @click="add"
            :icon="Plus"
            size="small">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            :icon="Delete"
            size="small">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            :icon="Upload"
            size="small">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            :icon="Download"
            size="small">导出
        </el-button>
      </el-col>

    </el-row>

    <el-table ref="reftest" v-loading="loading" stripe :data="accountList" style="width: 100%;">
      <el-table-column type="selection" min-width="40" align="center"/>
      <el-table-column prop="id" align="center" label="编号" min-width="60"/>
      <el-table-column prop="nickname" label="账号昵称" align="center" min-width="100"/>
      <el-table-column prop="gameAccount" label="游戏账号" align="center" min-width="100"/>
      <el-table-column prop="serverType" label="区服" align="center" min-width="80">
        <template #default="scope">
          <el-tag style="user-select: none" type="info">
            {{ scope.row.serverType === 0 ? '官服' : 'B服' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sane" label="理智" align="center" min-width="60"/>
      <el-table-column label="状态" align="center" min-width="80">
        <template #default="scope">

          <el-tag style="user-select: none" :type="scope.row.status === 0 ? 'info' : scope.row.status === 1 ? 'warning':scope.row.status === 2?'success':'danger'">
            {{ scope.row.status === 0 ? '正常' : scope.row.status === 1?'等待':scope.row.status === 2?'冷却':scope.row.status === 3?'异常':'停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="expireTime" label="过期时间" align="center" min-width="150"/>
      <el-table-column fixed="right" label="操作" align="center" min-width="80">
        <template #default="scope">
          <el-button
              size="small"
              link
              type="primary"
              :icon="Edit">修改
          </el-button>
          <el-button
              size="small"
              link
              type="danger"
              :icon="Delete">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
          size="small"
          v-model:current-page="queryParams.currentPage"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10,30, 50, 100]"
          :size="pages"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-dialog class="dialog-from" v-model="openDialog" :title="dialogTitle" width="300" center>
    <el-form :rules="rules" ref="ruleFormRef" size="default" :model="accountFrom">
      <el-form-item prop="gameInfo.gameAccount" label="账号">
        <el-input v-model="accountFrom.gameInfo.gameAccount" maxlength="11" minlength="5"/>
      </el-form-item>
      <el-form-item prop="gameInfo.gamePassword" label="密码">
        <el-input v-model="accountFrom.gameInfo.gamePassword" type="password" minlength="6" maxlength="20" show-password/>
      </el-form-item>
      <el-form-item prop="gameInfo.nickname" label="昵称">
        <el-input v-model="accountFrom.gameInfo.nickname" maxlength="30"/>
      </el-form-item>

      <el-form-item prop="email" label="邮箱">
        <el-input v-model="accountFrom.email"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button style="width: 100px" @click="openDialog = false">取消</el-button>
        <el-button style="width: 100px" type="primary" @click="handleClick(ruleFormRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style>
.box {
  display: flex;
  height: auto;
  width: 100%;
  flex-direction: column;
}

.cell .el-button {
  margin-left: 0;
}

.ellipsis .cell {
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号显示超出部分 */
  max-width: 200px;
}

.el-form {
  width: 100%;
  display: flex;
  align-items: start;
  flex-flow: wrap;
  justify-content: left;
}

.el-table {
  min-height: 300px
}

.mb8 {
  margin-bottom: 10px;
}

.mb8 .el-col {
  margin-top: 5px;
}

.page {
  width: 100%;
  height: auto;
  display: flex;
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
